package com.fulong.controller;

import java.sql.SQLException;
import java.util.*;
import java.util.logging.StreamHandler;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fulong.entity.DeviceLendRecordEntity;
import com.fulong.entity.DeviceStatusInfoEntity;
import com.fulong.entity.DeviceStatusInvoEntity;
import com.fulong.service.*;
import com.fulong.web.webconfig.UserStatus;
import org.apache.el.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fulong.entity.DeviceManageInfoEntity;
import com.fulong.common.utils.PageUtils;
import com.fulong.common.utils.R;
import com.baomidou.mybatisplus.core.conditions.Wrapper;


@RestController
@RequestMapping("/devicemanageinfo")
public class DeviceManageInfoController {
    private static Map<Integer ,Integer> status = new HashMap<>();

    static {   //映射状态
        //状态映射
        /* 借的人看的的设备
         * 0 --> 4 借 --> 审批中
         * 2 --> 5 通过 -- 审批成功
         * 3 --> 6 驳回 --> 审批未通过
         * */
        status.put(0 , 4);
        status.put(2 , 5);
        status.put(3 , 6);
        status.put(4, 7);
    }

    @Autowired
    private DeviceManageInfoService deviceManageInfoService ;
    @Autowired
    private DeviceLendRecordService deviceLendRecordService ;
    @Autowired
    private DeviceStatusInvoService deviceStatusInvoService;
    @Autowired
    private UserBaiseInfoService userBaiseInfoService;
    /*
    * 获取出库设备信息
    * */
    @RequestMapping("/getRepairInfo")
    public R getRepairInfo(@RequestBody Map<String, Object> params){
        PageUtils pageUtils = deviceLendRecordService.queryOutStockPage(params);
        return R.ok().put("page",pageUtils);
    }


    /*
    *
    *
    * */
    @RequestMapping("/outstock")
    public R outStock(@RequestBody Map<String, Object> params){
        String approverid = params.get("id").toString();
        String deviceid = params.get("deviceid").toString();
        Integer status = (int)params.get("status");
        boolean update = false;
        update = deviceLendRecordService.update(
                new UpdateWrapper<DeviceLendRecordEntity>()
                        .eq("id", approverid)
                        .set("status", status));
        switch (status){
            case 4 :
                break;
            case 5 :
            case 6 :
                boolean update1 = deviceManageInfoService.update(new UpdateWrapper<DeviceManageInfoEntity>()
                        .eq("id", approverid)
                        .set("status", 0));
                update = update&&update1;
                break;
            default:
                break;
        }
        return update ?  R.ok() : R.error();
    }


    public DeviceManageInfoEntity translateDao(Map<String, Object> params) {
        DeviceManageInfoEntity deviceManageInfoEntity = new DeviceManageInfoEntity();
        deviceManageInfoEntity.setCreattime(new Date());
        deviceManageInfoEntity.setStatus(5);
        if(params.get("type")!=null) {
            deviceManageInfoEntity.setType(params.get("type").toString());
        }else {
            return  null;
        }
        if(params.get("location")!=null) {
            deviceManageInfoEntity.setType(params.get("location").toString());
        }else {
            return null;
        }
        if(params.get("period")!=null) {
            deviceManageInfoEntity.setType(params.get("period").toString());
        }else {
            return null ;
        }
        return deviceManageInfoEntity ;
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> params) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException {

//        PageUtils page = deviceManageInfoService.queryPage(params);
        PageUtils page = deviceManageInfoService.queryPageAgent(params);
        return R.ok().put("page", page);
    }

    @RequestMapping("/currlist")
    public R currlist(@RequestBody Map<String, Object> params) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException {
        /*
        * 查询用户id
        * */
        PageUtils page = deviceManageInfoService.queryPageAgent(params);
        //拿出分页对象
        List<DeviceManageInfoEntity> list = (List<DeviceManageInfoEntity>) page.getList();
        //拿出当前用户借的设备
        List<DeviceLendRecordEntity> deviceid = deviceLendRecordService.list(new QueryWrapper<DeviceLendRecordEntity>().eq("userid" , UserStatus.getParam().getId()));
        //状态映射
        /* 借的人看的的设备
        * 0 --> 4 借 --> 审批中
        * 2 --> 5 通过 -- 审批成功
        * 3 --> 6 驳回 --> 审批未通过
        * */
        HashMap<String, Integer> map = new HashMap<>();
        for(DeviceLendRecordEntity el : deviceid) {
            map.put(el.getDeviceid() , el.getStatus());
        }
        list.stream().map(el -> {
            if(map.get(el.getId())!=null&&el.getStatus()!=0){
                el.setStatus(DeviceManageInfoController.status.get(map.get(el.getId())));
            }
            return el;
        }).collect(Collectors.toList());
        page.setList(list);
        return R.ok().put("page", page);
    }
    @Autowired
    private DeviceStatusInfoService deviceStatusInfoService;

    @RequestMapping("/currlistprocess")
    public R currlistprocess(@RequestBody Map<String, Object> params) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException {
        /*
         * 获取当前角色权限
         * */
        Integer role = userBaiseInfoService.getById(UserStatus.getParam().getId()).getRole();


        PageUtils page = deviceManageInfoService.queryPageAgent(params);
        //拿出分页对象
        List<DeviceManageInfoEntity> list = (List<DeviceManageInfoEntity>) page.getList();
        List<String> collect = list.stream().map(el -> el.getId()).collect(Collectors.toList());
        //拿出当前用户借的设备,且再查询列表中的
        List<DeviceLendRecordEntity> deviceid = deviceLendRecordService.list(
                new QueryWrapper<DeviceLendRecordEntity>()
                        .in("deviceid" , collect)
                        .eq("userid" , UserStatus.getParam().getId())
                        .eq("end" , 0)); //不统计终止的流程
        //获取当前审批状态
        List<Integer> statuscollect = deviceid.stream().map(el -> el.getStatus())
                .collect(Collectors.toList());
        if (statuscollect.size()==0) {
            statuscollect.add(-1000);//处理空异常
        }
        //查询当前角色的操作流程获取流程操作
        List<DeviceStatusInfoEntity> statusinfo = deviceStatusInfoService.list(
                new QueryWrapper<DeviceStatusInfoEntity>()
                        .in("statuscode" , statuscollect)
                        .eq("role" , role));
        //获取打断操作,当前角色可以执行的打断操作
        List<DeviceStatusInvoEntity> record = deviceStatusInvoService.list(
                new QueryWrapper<DeviceStatusInvoEntity>()
                        .in("record" , statuscollect)
                        .eq("role" , role));
        /*
        * 流程操作，和打断操作的角色不同相同
        * 优先构建流程操作，()
        * 如没有就会构建打断操作
        * 可以有多次操作
        * */
        //缓存流程
        HashMap<String, DeviceLendRecordEntity> map = new HashMap<>();
        for(DeviceLendRecordEntity el : deviceid) {
            map.put(el.getDeviceid() , el);
        }
        //缓存流程操作
        HashMap<Integer, DeviceStatusInfoEntity> option = new HashMap<>();
        for(DeviceStatusInfoEntity el : statusinfo) {
            option.put(el.getStatuscode() , el);
        }
        //缓存打断操作
        HashMap<Integer, DeviceStatusInvoEntity> invo = new HashMap<>();
        for(DeviceStatusInvoEntity el : record) {
            invo.put(el.getRecord() , el);
        }
        //操作单据
        list.stream().map(el -> {
            //当前设备的审批流程是否是当前用户角色可以操作的流程
            if(map.get(el.getId())!=null) {
                //如果可以操作写入操作
                Integer status = map.get(el.getId()).getStatus();
                if(option.get(status)!=null) {
                    el.setOption(deviceStatusInfoService.getoption(status));
                } else if(invo.get(status)!=null) {  //是否存在打断流程

                    el.setOption(
                            deviceStatusInfoService.list(
                                    new QueryWrapper<DeviceStatusInfoEntity>()
                                            .eq("statuscode" ,invo.get(status).getStatuscode())
                                            ));

                } else {
                    el.setOption(new LinkedList<>());
                }
                //设置流名称
                el.setProcessname(deviceStatusInfoService.getOne(
                        new QueryWrapper<DeviceStatusInfoEntity>()
                                .eq("statuscode" , status))
                        .getName());
                //附加上流程信息
                el.setLendrecord(map.get(el.getId()));
            } else {
                //设置好空操作
                el.setOption(new LinkedList<>());
            }

            return el;
        }).collect(Collectors.toList());
        //设置分页
        page.setList(list);


//
//
//
//
//
//
//        List<DeviceStatusInvoEntity> involist =
//                deviceStatusInvoService.list(
//                        new QueryWrapper<DeviceStatusInvoEntity>()
//                                .in("recordid", recordid));
//        HashMap<String, DeviceStatusInvoEntity> invomap = new HashMap<>();
//        for(DeviceStatusInvoEntity el : involist) {
//            invomap.put(el.getId(),el);
//        }
//
//        //方便下一步寻找
//        HashMap<String, Integer> map = new HashMap<>();
//        for(DeviceLendRecordEntity el : deviceid) {
//            map.put(el.getDeviceid() , el.getStatus());
//        }
//        list.stream().map(el -> {
//            if(map.get(el.getId())!=null&&invomap.get(el.getId())!=null){
//                if(role.equals(invomap.get(el.getId()).getRole())){
//                    el.setDisable(true);
//                    el.setOption(invomap.get(el.getId()).getName());
//                    el.setStatuscode(invomap.get(el.getId()).getStatuscode());
//                } else {
//                    el.setDisable(false);
//                    el.setOption("借用");
//                    el.setStatuscode(-1);
//                }
//            }
//            return el;
//        }).collect(Collectors.toList());
//        page.setList(list);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
		DeviceManageInfoEntity deviceManageInfo = deviceManageInfoService.getById(id);

        return R.ok().put("deviceManageInfo", deviceManageInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody DeviceManageInfoEntity deviceManageInfo){
        deviceManageInfo.setCreattime(new Date());
		deviceManageInfoService.save(deviceManageInfo);
        return R.ok().put("id" , deviceManageInfo.getId());
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody DeviceManageInfoEntity deviceManageInfo){
		deviceManageInfoService.updateById(deviceManageInfo);
        return R.ok();
    }
    /*
    * 取消审批
    * */
    @RequestMapping("/cancelapprover")
    public R cancelApprover(@RequestBody DeviceManageInfoEntity deviceManageInfo){
        deviceManageInfoService.updateById(deviceManageInfo);
        boolean update = deviceLendRecordService.update(new UpdateWrapper<DeviceLendRecordEntity>()
                .eq("deviceid", deviceManageInfo.getId())
                .eq("userid", UserStatus.getParam().getId())
                .eq("status" , 0)
                .set("status", 1));
        return R.ok();
    }

    /*
    * 归还审批
    * */
    @RequestMapping("/cancelbackapprover")
    public R backDeviceApprover(@RequestBody DeviceManageInfoEntity deviceManageInfo){
        deviceManageInfoService.updateById(deviceManageInfo);
        boolean update = deviceLendRecordService.update(new UpdateWrapper<DeviceLendRecordEntity>()
                .eq("deviceid", deviceManageInfo.getId())
                .eq("userid", UserStatus.getParam().getId())
                .eq("status" , 4)
                .set("status", 7));
        return R.ok();
    }
    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody String[] ids){
		deviceManageInfoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
    /*
    * 设备维护计划
    * */
    @RequestMapping("/maintianDevice")
    public R maintianDevice(){

        return R.ok();
    }
}
